package org.example;

import java.util.ArrayDeque;
import java.util.Deque;

public class Test6 {
    //leetcode 226 反转二叉树 https://leetcode.cn/problems/invert-binary-tree/description/

    /**
     * dfs
     * @param root
     * @return
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        invertTree(root.left);
        invertTree(root.right);
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        return root;
    }

    /**
     * bfs
     * @param root
     * @return
     */
    public TreeNode invertTree1(TreeNode root) {
        if (root == null) return root;
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);
        while (!deque.isEmpty()) {
            int count = deque.size();
            while (count > 0) {
                TreeNode tmp = deque.poll();
                if (tmp.left != null) deque.add(tmp.left);
                if (tmp.right != null) deque.add(tmp.right);
                TreeNode node = tmp.left;
                tmp.left = tmp.right;
                tmp.right = node;
                count--;
            }
        }
        return root;
    }
}
